package com.kaizeli.website.filter;

import com.kaizeli.website.constant.JwtConstant;
import com.kaizeli.website.context.BaseContext;
import com.kaizeli.website.exception.BusinessErrorEnum;
import com.kaizeli.website.exception.BusinessException;
import com.kaizeli.website.util.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import jakarta.servlet.http.HttpServletRequest;

public class JwtFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader(JwtConstant.HEADER_STRING);

        if (authHeader != null && authHeader.startsWith(JwtConstant.TOKEN_PREFIX)) {
            String token = authHeader.substring(JwtConstant.TOKEN_PREFIX.length());

            if (JwtUtil.validateToken(token)) {
                String username = JwtUtil.getUsernameFromToken(token);
                boolean isAdmin = JwtUtil.isAdminFromToken(token);
                BaseContext.setCurrentId(username);
                request.setAttribute("username", username);
                request.setAttribute("admin", isAdmin);
                return true;
            }
        }

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        throw new BusinessException(BusinessErrorEnum.USER_NOT_LOGIN);
    }
}